package com.example.lcl.exp2019_1;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;

public class StopWatchService extends Service {

    //新线程
    private Thread workerThread;
    private Intent intent;
    private int flag;
    public StopWatchService(){}

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //创建新线程
        workerThread = new Thread(null,backgroundWork,"WorkThread");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.intent = intent;
        if (!workerThread.isAlive()) {
            workerThread.start(); //启动新线程
        }
        flag = intent.getIntExtra("flag",0);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        workerThread.interrupt(); //终止新线程
    }

    //新线程代码部分
    private  Runnable backgroundWork=new Runnable() {
        @Override
        public void run() {
            try{
                int second = intent.getIntExtra("data",0);
                while (!Thread.interrupted()){
                    //MainActivity.UpdateUI(Math.random());
                    if (flag == 1) {
                        second += 10;
                        flag = 0;
                    }
                    else second++;
                    //通过消息发送界面更新数据
                    Message msg=Message.obtain(); //创建消息对象
                    msg.what=MainActivity.MSGID_1; //设定消息ID--可选，如果只有一个消息，不用设置
                    Bundle bundle=new Bundle();
                    bundle.putInt("data",second); //准备消息对象附带的的数据
                    msg.setData(bundle); //设置消息附带数据
                    MainActivity.myMainHandler.sendMessage(msg); //发送消息，发送后，不等待，继续执行

                    Thread.sleep(1000);
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    };
}
